<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Flutter中key的作用》 - Lucklyの博客 - 在阅读中遇见自己</title><meta name="Description" content="早起的年轻人做的网站"><meta property="og:title" content="《Flutter中key的作用》" />
<meta property="og:description" content="
本文主要介绍
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://luckly.work/flutter%E4%B8%ADkey%E7%9A%84%E4%BD%9C%E7%94%A8/" />
<meta property="og:image" content="https://luckly.work/logo.png"/>
<meta property="article:published_time" content="2021-07-26T22:52:25+08:00" />
<meta property="article:modified_time" content="2021-07-26T22:52:25+08:00" />
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://luckly.work/logo.png"/>

<meta name="twitter:title" content="《Flutter中key的作用》"/>
<meta name="twitter:description" content="
本文主要介绍
"/>
<meta name="application-name" content="LoveIt">
<meta name="apple-mobile-web-app-title" content="LoveIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://luckly.work/flutter%E4%B8%ADkey%E7%9A%84%E4%BD%9C%E7%94%A8/" /><link rel="prev" href="https://luckly.work/%E6%A1%88%E4%BE%8B%E5%88%86%E6%9E%907/" /><link rel="next" href="https://luckly.work/dart%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80%E4%B9%8Bstring/" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.13.0/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.7.2/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Flutter中key的作用》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/luckly.work\/flutter%E4%B8%ADkey%E7%9A%84%E4%BD%9C%E7%94%A8\/"
        },"image": [{
                            "@type": "ImageObject",
                            "url": "https:\/\/luckly.work\/images\/Apple-Devices-Preview.png",
                            "width":  3200 ,
                            "height":  2048 
                        }],"genre": "posts","keywords": "flutter","wordcount":  3057 ,
        "url": "https:\/\/luckly.work\/flutter%E4%B8%ADkey%E7%9A%84%E4%BD%9C%E7%94%A8\/","datePublished": "2021-07-26T22:52:25+08:00","dateModified": "2021-07-26T22:52:25+08:00","license": "This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.","publisher": {
            "@type": "Organization",
            "name": "xxxx","logo": {
                    "@type": "ImageObject",
                    "url": "https:\/\/luckly.work\/images\/avatar.png",
                    "width":  528 ,
                    "height":  560 
                }},"author": {
                "@type": "Person",
                "name": "早起的年轻人"
            },"description": ""
    }
    </script></head>
    <body header-desktop="fixed" header-mobile="auto"><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><div class="logo-wrapper">
  <a href="/%20/" class="logo">Lucklyの博客 - 在阅读中遇见自己</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
      <a class="menu-item-link" href="/posts/">所有文章</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/flutter/">Flutter</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/read/">读书笔记</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/go/">Go</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/tags/">标签</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/categories/">分类</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/about/">关于</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="https://github.com/ITmxs">Github</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/friend/">友链</a>
    </li>
  </ul>
</nav><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Flutter中key的作用》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>早起的年轻人</a></span>&nbsp;<span class="post-category">收录于 <a href="/categories/flutter/"><i class="far fa-folder fa-fw"></i>Flutter</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-07-26">2021-07-26</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 3057 字&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 7 分钟&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>目录</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li><a href="#key的定义">key的定义</a></li>
        <li><a href="#key的作用">Key的作用</a>
          <ul>
            <li><a href="#无状态组件">无状态组件</a></li>
            <li><a href="#有状态组件">有状态组件</a></li>
          </ul>
        </li>
        <li><a href="#key的分类">Key的分类</a></li>
        <li><a href="#何时使用key">何时使用key</a>
          <ul>
            <li><a href="#valuekey">ValueKey</a></li>
            <li><a href="#objectkey">ObjectKey</a></li>
            <li><a href="#uniquekey">UniqueKey</a></li>
            <li><a href="#pagestoragekey">PageStorageKey</a></li>
            <li><a href="#globalkey">GlobalKey</a>
              <ul>
                <li><a href="#用途1">用途1</a></li>
                <li><a href="#用途2">用途2</a></li>
              </ul>
            </li>
          </ul>
        </li>
        <li><a href="#参考资料">参考资料</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要介绍</p>
</blockquote>
<h2 id="key的定义">key的定义</h2>
<p>Key Class官方介绍：</p>
<blockquote>
<p>A [Key] is an identifier for [Widget]s, [Element]s and [SemanticsNode]s.</p>
<p>A new widget will only be used to update an existing element if its key is</p>
<p>the same as the key of the current widget associated with the element.</p>
<p>{@youtube 560 315 <a href="https://www.youtube.com/watch?v=kn0EOS-ZiIc%7D">https://www.youtube.com/watch?v=kn0EOS-ZiIc}</a></p>
<p>Keys must be unique amongst the [Element]s with the same parent.</p>
<p>Subclasses of [Key] should either subclass [LocalKey] or [GlobalKey].</p>
</blockquote>
<p>翻译过来：</p>
<blockquote>
<p>一个Key是Widget，Element以及SemanticsNode的标识。</p>
<p>一个新widget将仅用来更新一个已存在的element假如它的key和当前widget关联的元素一致。</p>
<p>官方介绍视频 <a href="https://www.youtube.com/watch?v=kn0EOS-ZiIc">https://www.youtube.com/watch?v=kn0EOS-ZiIc</a></p>
<p>在有着相同父节点的element中，Key必须是唯一的。</p>
<p>Key的子类要么是LocalKey，要么是GlobalKey。</p>
</blockquote>
<p>Key 官方介绍：</p>
<blockquote>
<p>Controls how one widget replaces another widget in the tree.</p>
<p>If the <a href="https://api.flutter.dev/flutter/widgets/Widget/dart-core/Object/runtimeType.html" target="_blank" rel="noopener noreffer">runtimeType</a> and <a href="https://api.flutter.dev/flutter/widgets/Widget/widgets/Widget/key.html" target="_blank" rel="noopener noreffer">key</a> properties of the two widgets are <a href="https://api.flutter.dev/flutter/widgets/Widget/widgets/Widget/operator_equals.html" target="_blank" rel="noopener noreffer">operator==</a>, respectively, then the new widget replaces the old widget by updating the underlying element (i.e., by calling <a href="https://api.flutter.dev/flutter/widgets/Widget/widgets/Element/update.html" target="_blank" rel="noopener noreffer">Element.update</a>with the new widget). Otherwise, the old element is removed from the tree, the new widget is inflated into an element, and the new element is inserted into the tree.</p>
<p>In addition, using a <a href="https://api.flutter.dev/flutter/widgets/Widget/widgets/GlobalKey-class.html" target="_blank" rel="noopener noreffer">GlobalKey</a> as the widget’s <a href="https://api.flutter.dev/flutter/widgets/Widget/widgets/Widget/key.html" target="_blank" rel="noopener noreffer">key</a> allows the element to be moved around the tree (changing parent) without losing state. When a new widget is found (its key and type do not match a previous widget in the same location), but there was a widget with that same global key elsewhere in the tree in the previous frame, then that widget’s element is moved to the new location.</p>
<p>Generally, a widget that is the only child of another widget does not need an explicit key.</p>
</blockquote>
<p>翻译过来：</p>
<blockquote>
<p>控制一个小部件如何替换树中的另一个小部件。</p>
<p>如果两个widget的<a href="https://api.flutter.dev/flutter/dart-core/Object/runtimeType.html" target="_blank" rel="noopener noreffer">runtimeType</a>和<a href="https://api.flutter.dev/flutter/widgets/Widget/key.html" target="_blank" rel="noopener noreffer">key</a>属性分别是相等的(<a href="https://api.flutter.dev/flutter/widgets/Widget/operator_equals.html" target="_blank" rel="noopener noreffer">==</a>)，则新widget通过更新基础element（即，通过使用新的widget调用<a href="https://api.flutter.dev/flutter/widgets/Element/update.html" target="_blank" rel="noopener noreffer">Element.update</a>）来替换旧widget。否则，将从树中删除旧element，将新widget放大为一个element，然后将新element插入到树中。</p>
<p>另外，使用<a href="https://api.flutter.dev/flutter/widgets/GlobalKey-class.html" target="_blank" rel="noopener noreffer">GlobalKey</a>作为窗口小部件的<a href="https://api.flutter.dev/flutter/widgets/Widget/key.html" target="_blank" rel="noopener noreffer">key</a>允许该element在树上移动（更改父级）而不会丢失状态。当找到新的widget（其键和类型与相同位置的先前widget不匹配），但是在前一帧的树中其他位置有一个具有相同全局键的widget时，该widget的element将移至新位置。</p>
<p>通常，作为另一个widget的唯一child的widget不需要显式key。</p>
</blockquote>
<h2 id="key的作用">Key的作用</h2>
<p>大多数时候并不需要使用key。</p>
<p>当需要在一个<strong>StatefulWidget</strong>集合中进行添加、删除、重排序等操作时，才是key登场的时候。</p>
<h3 id="无状态组件">无状态组件</h3>
<p>下面这段代码在一个Row中展示了两个彩色方片（StatelessContainer），当点击按钮时，会交换两个方片的位置：</p>
<p><a href="https://blog.wangruofeng007.com/images/flutter_key/img_key_screen.png" target="_blank" rel="noopener noreffer"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/img_key.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/img_key.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/img_key.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/img_key.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/img_key.png"
        title="img_key_screen" /></a></p>
<p>代码如下</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">import &#39;dart:math&#39;;
import &#39;package:flutter/material.dart&#39;;

class StatelessContainer extends StatelessWidget {
  final Color color = Color.fromRGBO(
      Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100,
      height: 100,
      color: color,
    );
  }
}

class Screen extends StatefulWidget {
  @override
  _ScreenState createState() =&gt; _ScreenState();
}

class _ScreenState extends State&lt;Screen&gt; {
  List&lt;Widget&gt; widgets = [
    StatelessContainer(),
    StatelessContainer(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: widgets,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: switchWidget,
        child: Icon(Icons.undo),
      ),
    );
  }

  switchWidget() {
    widgets.insert(0, widgets.removeAt(1));
    setState(() {});
  }
}
</code></pre></td></tr></table>
</div>
</div><h3 id="有状态组件">有状态组件</h3>
<p>有状态组件的状态信息（如颜色）通常是存储在state中的，而state是存储在element树中的。</p>
<p>那么Key到底应该用到哪呢？
我们再来一个例子，我们把色块用Padding包装一下。运行之后会发现，色块并没有交换，而是以随机的形式在变换颜色。为什么呢？</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span><span class="lnt">56
</span><span class="lnt">57
</span><span class="lnt">58
</span><span class="lnt">59
</span><span class="lnt">60
</span><span class="lnt">61
</span><span class="lnt">62
</span><span class="lnt">63
</span><span class="lnt">64
</span><span class="lnt">65
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">import &#39;dart:math&#39;;
import &#39;package:flutter/material.dart&#39;;

class Screen extends StatefulWidget {
  Screen({Key key}) : super(key: key);

  @override
  _ScreenState createState() =&gt; _ScreenState();
}

class _ScreenState extends State&lt;Screen&gt; {
  List&lt;Widget&gt; widgets = [
    Padding(
      padding: const EdgeInsets.all(8.0),
      child: StatefulContainer(key: UniqueKey()),
    ),
    Padding(
      padding: const EdgeInsets.all(8.0),
      child: StatefulContainer(key: UniqueKey()),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: widgets,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: switchWidget,
        child: Icon(Icons.undo),
      ),
    );
  }

  switchWidget() {
    widgets.insert(0, widgets.removeAt(1));
    setState(() {});
    print(&#39;${widgets[0]}, ${widgets[1]}&#39;);
  }
}

class StatefulContainer extends StatefulWidget {
  StatefulContainer({Key key}) : super(key: key);

  @override
  _StatefulContainerState createState() =&gt; _StatefulContainerState();
}

class _StatefulContainerState extends State&lt;StatefulContainer&gt; {
  final Color color = Color.fromRGBO(
      Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
      width: 100,
      height: 100,
    );
  }
}
</code></pre></td></tr></table>
</div>
</div><p>结合我们上面的理论，我们分析一下这次的Widget Tree 和 Element Tree，当我们交换元素后，Flutter element-to-widget matching algorithm,(元素-组件匹配算法)，开始进行对比，算法每次只对比一层，即Padding这一层。显然，Padding并没有发生本质的变化。</p>
<p>于是开始进行第二层对比，在对比时Flutter发现元素与组件的Key并不匹配，于是，把它设置成不可用状态，但是这里所使用的Key只是本地Key（Local Key），Flutter并不能找到另一层里面的Key（即另外一个Padding Widget中的Key）所以，Flutter就创建了一个新的Widget，而这个Widget的颜色就成了我们看到的『随机色』。</p>
<p>通过上面的示例，我们能明显的看出，我们的Key要设置到组件树的 <strong>顶层</strong>，而这一层在改变时，才能复用或者更新状态。</p>
<p>修正版本：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span><span class="lnt">56
</span><span class="lnt">57
</span><span class="lnt">58
</span><span class="lnt">59
</span><span class="lnt">60
</span><span class="lnt">61
</span><span class="lnt">62
</span><span class="lnt">63
</span><span class="lnt">64
</span><span class="lnt">65
</span><span class="lnt">66
</span><span class="lnt">67
</span><span class="lnt">68
</span><span class="lnt">69
</span><span class="lnt">70
</span><span class="lnt">71
</span><span class="lnt">72
</span><span class="lnt">73
</span><span class="lnt">74
</span><span class="lnt">75
</span><span class="lnt">76
</span><span class="lnt">77
</span><span class="lnt">78
</span><span class="lnt">79
</span><span class="lnt">80
</span><span class="lnt">81
</span><span class="lnt">82
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">import &#39;dart:math&#39;;

import &#39;package:flutter/material.dart&#39;;

class Screen extends StatefulWidget {
  Screen({Key key}) : super(key: key);

  @override
  _ScreenState createState() =&gt; _ScreenState();
}

class _ScreenState extends State&lt;Screen&gt; {
  List&lt;Widget&gt; widgets = [
    Padding(
      key: UniqueKey(),
      padding: const EdgeInsets.all(8.0),
      child: StatefulContainer(),
    ),
    Padding(
      key: UniqueKey(),
      padding: const EdgeInsets.all(8.0),
      child: StatefulContainer(),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: widgets,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: switchWidget,
        child: Icon(Icons.undo),
      ),
    );
  }

  switchWidget() {
    widgets.insert(0, widgets.removeAt(1));
    setState(() {});
    print(&#39;${widgets[0]}, ${widgets[1]}&#39;);
  }
}

class StatelessContainer extends StatelessWidget {
  final Color color = Color.fromRGBO(
      Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
      width: 100,
      height: 100,
    );
  }
}

class StatefulContainer extends StatefulWidget {
  StatefulContainer({Key key}) : super(key: key);

  @override
  _StatefulContainerState createState() =&gt; _StatefulContainerState();
}

class _StatefulContainerState extends State&lt;StatefulContainer&gt; {
  final Color color = Color.fromRGBO(
      Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
      width: 100,
      height: 100,
    );
  }
}
</code></pre></td></tr></table>
</div>
</div><h2 id="key的分类">Key的分类</h2>
<p><a href="https://blog.wangruofeng007.com/images/flutter_key/img_key.png" target="_blank" rel="noopener noreffer"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/img_key.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/img_key.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/img_key.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/img_key.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/img_key.png"
        title="img_key" /></a></p>
<ul>
<li>ValueKey:以一个值为key。</li>
<li>ObjectKey:以一个对象为key。</li>
<li>UniqueKey:生成唯一的随机数作为key。</li>
<li>PageStorageKey:专用于存储页面滚动位置的key。</li>
<li>GlobalKey:见后文。</li>
</ul>
<h2 id="何时使用key">何时使用key</h2>
<h3 id="valuekey">ValueKey</h3>
<p>如果您有一个 Todo List 应用程序，它将会记录你需要完成的事情。我们假设每个 Todo 事情都各不相同，而你想要对每个 Todo 进行滑动删除操作。</p>
<p>这时候就需要使用 ValueKey！</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">return TodoItem(
    key: ValueKey(todo.task),
    todo: todo,
    onDismissed: (direction){
        _removeTodo(context, todo);
    },
);
</code></pre></td></tr></table>
</div>
</div><h3 id="objectkey">ObjectKey</h3>
<p>如果你有一个生日应用，它可以记录某个人的生日，并用列表显示出来，同样的还是需要有一个滑动删除操作。</p>
<p>我们知道人名可能会重复，这时候你无法保证给 Key 的值每次都会不同。但是，当人名和生日组合起来的 Object 将具有唯一性。</p>
<p>这时候你需要使用 ObjectKey！</p>
<h3 id="uniquekey">UniqueKey</h3>
<p>如果组合的 Object 都无法满足唯一性的时候，你想要确保每一个 Key 都具有唯一性。那么，你可以使用 UniqueKey。它将会通过该对象生成一个具有唯一性的 hash 码。</p>
<p>不过这样做，每次 Widget 被构建时都会去重新生成一个新的 UniqueKey，失去了一致性。也就是说你的小部件还是会改变。（还不如不用😂）</p>
<h3 id="pagestoragekey">PageStorageKey</h3>
<p>当你有一个滑动列表，你通过某一个 Item 跳转到了一个新的页面，当你返回之前的列表页面时，你发现滑动的距离回到了顶部。这时候，给 Sliver 一个 PageStorageKey！它将能够保持 Sliver 的滚动状态。</p>
<h3 id="globalkey">GlobalKey</h3>
<p>每个globalkey都是一个在整个应用内唯一的key。</p>
<p>globalkey相对而言是比较昂贵的，如果你并不需要globalkey的某些特性，那么可以考虑使用Key、ValueKey、ObjectKey或UniqueKey。</p>
<h4 id="用途1">用途1</h4>
<p>允许widget在应用程序中的任何位置更改其parent而不丢失其状态。应用场景：在两个不同的屏幕上显示相同的widget，并保持状态相同。</p>
<h4 id="用途2">用途2</h4>
<p>GlobalKey 能够跨 Widget 访问状态。 在这里我们有一个 Switcher 小部件，它可以通过 changeState 改变它的状态。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">class SwitcherScreenState extends State&lt;SwitcherScreen&gt; {
  bool isActive = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Switch.adaptive(
            value: isActive,
            onChanged: (bool currentStatus) {
              isActive = currentStatus;
              setState(() {});
            }),
      ),
    );
  }

  changeState() {
    isActive = !isActive;
    setState(() {});
  }
}
</code></pre></td></tr></table>
</div>
</div><p>但是我们想要在外部改变该状态，这时候就需要使用 GlobalKey。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">class _ScreenState extends State&lt;Screen&gt; {
  final GlobalKey&lt;SwitcherScreenState&gt; key = GlobalKey&lt;SwitcherScreenState&gt;();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SwitcherScreen(
        key: key,
      ),
      floatingActionButton: FloatingActionButton(onPressed: () {
        key.currentState.changeState();
      }),
    );
  }
}
</code></pre></td></tr></table>
</div>
</div><p>这里我们通过定义了一个 GlobalKey 并传递给 SwitcherScreen。然后我们便可以通过这个 key 拿到它所绑定的 SwitcherState 并在外部调用 changeState 改变状态了。</p>
<h2 id="参考资料">参考资料</h2>
<ul>
<li><a href="https://www.youtube.com/watch?v=kn0EOS-ZiIc&amp;feature=youtu.be" target="_blank" rel="noopener noreffer">何时使用密钥 - Flutter小部件 101 第四集</a></li>
<li><a href="https://flutter.dev/docs/development/ui/widgets-intro#keys" target="_blank" rel="noopener noreffer">widgets-intro#keys</a></li>
<li><a href="https://juejin.im/post/5ca2152f6fb9a05e1a7a9a26" target="_blank" rel="noopener noreffer">Flutter | 深入浅出Key</a></li>
<li><a href="https://blog.csdn.net/al4fun/article/details/95854045" target="_blank" rel="noopener noreffer">Flutter中的Key和GlobalKey</a></li>
</ul></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>更新于 2021-07-26</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://luckly.work/flutter%E4%B8%ADkey%E7%9A%84%E4%BD%9C%E7%94%A8/" data-title="《Flutter中key的作用》" data-hashtags="flutter"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://luckly.work/flutter%E4%B8%ADkey%E7%9A%84%E4%BD%9C%E7%94%A8/" data-hashtag="flutter"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Hacker News" data-sharer="hackernews" data-url="https://luckly.work/flutter%E4%B8%ADkey%E7%9A%84%E4%BD%9C%E7%94%A8/" data-title="《Flutter中key的作用》"><i class="fab fa-hacker-news fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://luckly.work/flutter%E4%B8%ADkey%E7%9A%84%E4%BD%9C%E7%94%A8/" data-title="《Flutter中key的作用》"><i data-svg-src="https://cdn.jsdelivr.net/npm/simple-icons@2.14.0/icons/line.svg"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://luckly.work/flutter%E4%B8%ADkey%E7%9A%84%E4%BD%9C%E7%94%A8/" data-title="《Flutter中key的作用》" data-image="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"><i class="fab fa-weibo fa-fw"></i></a></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/flutter/">flutter</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">返回</a></span>&nbsp;|&nbsp;<span><a href="/">主页</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/%E6%A1%88%E4%BE%8B%E5%88%86%E6%9E%907/" class="prev" rel="prev" title="《案例分析7》"><i class="fas fa-angle-left fa-fw"></i>《案例分析7》</a>
            <a href="/dart%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80%E4%B9%8Bstring/" class="next" rel="next" title="《Dart语言基础之String》">《Dart语言基础之String》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">早起的年轻人</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank">CC BY-NC 4.0</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.css"><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/autocomplete.js@0.37.1/dist/autocomplete.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/algoliasearch@4.2.0/dist/algoliasearch-lite.umd.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lazysizes@5.2.2/lazysizes.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharer.js@0.4.0/sharer.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":10},"comment":{},"cookieconsent":{"content":{"dismiss":"同意","link":"了解更多","message":"本网站使用 Cookies 来改善您的浏览体验."},"enable":true,"palette":{"button":{"background":"#f0f0f0"},"popup":{"background":"#1aa3ff"}},"theme":"edgeless"},"search":{"algoliaAppID":"PASDMWALPK","algoliaIndex":"index.zh-cn","algoliaSearchKey":"b42948e51daaa93df92381c8e2ac0f93","highlightTag":"em","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":50,"type":"algolia"}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
